export function getChildrenNode(ele) {
  const children = Array.from(ele.childNodes);
  const rel = [];
  for (let i = 0; i < children.length; i++) {
    if (children[i].nodeName !== '#text') {
      rel.push(children[i]);
    }
  }
  return rel;
}

// 获取dom元素dataset中的值
export function getValByDom(ele, key) {
  if (!ele) {
    return null;
  }
  const childrenNodes = getChildrenNode(ele);
  if (ele.dataset[key]) {
    return ele.dataset[key];
  }
  let dataKey = ele.dataset.key;
  if (!dataKey) {
    const dataKeyDom = ele.querySelector('[data-key]');
    if (!dataKeyDom) {
      return 'noType';
    }
    if (dataKeyDom.dataset[key]) {
      return dataKeyDom.dataset[key];
    }
    dataKey = ele.querySelector('[data-key]').dataset.key;
  }
  // 根据key获取带有类型的dom
  const thisTypeDom = ele.querySelector(`[data-key="${dataKey}"] [data-slate-type]`);
  if (thisTypeDom) {
    return thisTypeDom.dataset[key];
  }
  return 'noType';
}

export function getScrollVal() {
  const body = document.querySelector('body');
  const html = document.querySelector('html');
  const scrollTop = html.scrollTop || body.scrollTop;
  const scrollLeft = html.scrollLeft || body.scrollLeft;
  return {
    scrollTop,
    scrollLeft,
  };
}

/**
 * 计算传入dom元素,输入当前dom与body间的相对位置body左上角坐标为（0，0） 输出{x:number, y:number}
 */
export function positionFromBody(ele, positionObj = {x: 0, y: 0}) {
  if (!ele) {
    return {
      x: 0,
      y: 0,
    };
  }
  const body = document.body;
  const offsetParent = (ele.offsetParent) || body;
  const positionVal = {...positionObj};
  positionVal.x += ele.offsetLeft;
  positionVal.y += ele.offsetTop;
  if (body === offsetParent) {
    return positionVal;
  }
  return positionFromBody(offsetParent, positionVal);

}
